import { getEnums } from '@/api/system/enum'
import { EnumDataVO } from '@/api/system/enum/types'
import { useI18n } from 'vue-i18n'

/**
 * 获取字典数据
 */
export const useEnum = (...args: string[]): { [key: string]: EnumDataOption[] } => {
  const { t } = useI18n()
  const res = ref<{
    [key: string]: EnumDataOption[]
  }>({})

  const underlineToHump = (str: string) => {
    const a = str.split('_')
    let result = ''
    for (let i = 0; i < a.length; i++) {
      result = result + a[i].slice(0, 1).toUpperCase() + a[i].slice(1)
    }
    return result
  }

  const convertEnum = (data: any) => {
    for (let i = 0; i < data.length; i++) {
      data[data[i].value] = {
        value: data[i].value,
        label: data[i].label,
      }
    }

    return data
  }

  const processI18n = (enumType, data: EnumDataVO[]) => {
    const type = enumType.charAt(0).toLowerCase() + enumType.slice(1)
    for (const index in data) {
      const value = data[index].enumValue.charAt(0).toLowerCase() + data[index].enumValue.slice(1)
      data[index].enumLabel = t(`enum.${type}.${value}`)
    }
    return data
  }

  return (() => {
    args.forEach(async (enumType) => {
      enumType = underlineToHump(enumType)
      res.value[enumType] = []
      await getEnums(enumType).then((resp) => {
        const data: EnumDataVO[] = processI18n(enumType, resp.data)
        const options = data.map((p): EnumDataOption => ({ label: p.enumLabel, value: p.enumValue, elTagType: p.listClass, elTagClass: p.cssClass }))
        res.value[enumType] = convertEnum(options)
      })
    })
    return res.value
  })()
}
